# -*- coding:UTF-8 -*-
# 开发人员: limenghui
# 开发时间：2024-09-22 上午11:06
# 文件名称：
# 开发工具：pycharm

# pdf = pdfplumber.open(r"shanxi_9_1.pdf")
# first_page = pdf.pages[0]
# text = first_page.extract_text()
# table = first_page.extract_tables()
# print(pdf.metadata)
# print(table)


import cv2
import os
import fitz
from PIL import Image
import paddleocr
from paddleocr import PaddleOCR
from paddleocr import PPStructure, save_structure_res
from paddleocr.ppstructure.recovery.recovery_to_doc import sorted_layout_boxes, convert_info_docx


path1 = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\gk_files\gk_pdf'
path2 = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\gk_files\pdf_split_png'
# pdf_file = 'shanxi_9_2.pdf'
# pdf_file = 'shanghai_6.pdf'
pdf_file = 'xiamen_24_5_1.pdf'
pdf_nm = pdf_file .replace('.pdf','')

subpath = os.path.join(path2,pdf_nm)
isExists = os.path.exists(subpath)
if not isExists:
    os.makedirs(subpath)

# with fitz.open(os.path.join(path1,pdf_file)) as pdf:
#     for pg in range(0, pdf.page_count):
#         page = pdf[pg]
#         # 设置缩放和旋转系数,zoom_x, zoom_y取相同值，表示等比例缩放
#         mat = fitz.Matrix(2, 2)
#         pm = page.get_pixmap(matrix=mat, alpha=False)
#         # if width or height > 2000 pixels, don't enlarge the image
#         if pm.width > 2000 or pm.height > 2000:
#             pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
#         page_num = pg + 1  # 页码从1开始
#         file_name = str(page_num) + '_' + str(pdf_nm) + '.png'
#         pm.save(os.path.join(subpath,file_name))  # 第1张图片名：1.png，以此类推
#
#
# # 使用默认模型路径
# paddleocr = PaddleOCR(lang='ch', show_log=False)
# pic_path  = os.path.join(path2,pdf_nm)
# pic_list = os.listdir(pic_path) # 该目录下的所有文件
# for pic in pic_list:
#     img = cv2.imread(os.path.join(pic_path,pic))  # 打开需要识别的图片
#     result = paddleocr.ocr(img)
#     for i in range(len(result[0])):
#         print(result[0][i][1][0])   # 输出识别结果
#



table_engine = PPStructure(show_log=True)

save_folder = './output'
# img_path = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\gk_files\pdf_split_png\shanxi_9_1\2_shanxi_9_1.png'
# img_path = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\gk_files\pdf_split_png\shanghai_6\1_shanghai_6.png'
# img_path = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\gk_files\pdf_split_png\xiamen_24_5_1\2_xiamen_24_5_1.png'
img_path = r'C:\Users\limenghui\PycharmProjects\CITIC_BANK\WORK\xiamen.png'
img = cv2.imread(img_path)
result = table_engine(img)
# 保存结果到输出目录的一个文件中，这个文件夹和输入同名，并包含页面识别的表格和html结果
save_structure_res(result, save_folder,os.path.basename(img_path).split('.')[0])
print(result[1],type(result[1]))
for line in result:
    line.pop('img')
    print(line)
